﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseAccess;
using System.Data;
using Liguo.AppCode;
using System.Text.RegularExpressions;

namespace Liguo.Store
{
    public partial class Display : System.Web.UI.Page
    {
        PagedDataSource pds;                //开发包封装好的   用于分页适配的类 
        DataSet dataset;
        int CurrentPageIndex;           //当前页索引
        static String GOODSTABLENAME = "GoodsInfo";//商品的表名
        static String FIELD = "PicturePath,GoodsName,Price,ID";
        public String goodsinfo;
        protected void Page_Load(object sender, EventArgs e)
        {
            //如果用户登录，返回信息；否则无
            if (Session["User"] != null)
            {
                goodsinfo = JsonConvert.GetGoodsInfoJson(((User)Session["User"]).UserID);
            }

            String TypeId = Request.QueryString["type"];   //store首页左侧的商品类型       
            String KeyWord = Request.Form["keyword"];  //上方的关键字
            pds = new PagedDataSource();
            SqlIt sql = new SqlIt();      //用来访问数据库的接口  来自唐经理  
            // dataset = sql.SelectAll("GoodsInfo", "PicturePath,GoodsName,Price");

            dataset = vagueSearch(sql, TypeId, KeyWord);       //模糊查询
            if (!Page.IsPostBack)
            {
                updatePageDataSource();           //初始化分页的一些参数
                ViewState["PageCount"] = pds.PageCount;    //会话session 对整个 application 有效 ，而视图状态 viewstate相当于某个页面的 session
                ViewState["CurrPageIndex"] = 0;
            }
            else
            {
                //updatePageDataSource();
            }
            this.TotalLbl.Text = pds.PageCount.ToString();//显示总页数
            this.DataListBind();            //不可以放在初始化条件之前就绑定，那样的话，如果仅有一页的数据，“下一页”页仍然显示
        }

        public DataSet vagueSearch(SqlIt sql, String type, String keyword)        //模糊查询的代码
        {
            if (type == null)
                type = "";
            if (keyword == null)
                keyword = "";
            String condition = "(Tags LIKE '%" + keyword + "%')";
            bool addbool = type.Equals("");
            if (addbool == false)
                condition += "and (Type=" + type + ")";

            return sql.SpecialItem(GOODSTABLENAME, condition, FIELD);
        }

        public void updatePageDataSource()
        {
            pds.DataSource = dataset.Tables[0].DefaultView; //将查询到的源数据  导入分页的源数据中
            pds.AllowPaging = true;     //允许分页
            pds.PageSize = 12;          //每页的大小

        }
        //将数据绑定到Datalist控件
        public void DataListBind()
        {
            updatePageDataSource();
            pds.CurrentPageIndex = (int)ViewState["CurrPageIndex"];
            DataList1.DataSource = pds;

            /*if (pds.PageCount< 2)
            {
                FirstLB.Visible = false;
                PreviousLB.Visible = false;
                NextLB.Visible = false;
                EndLB.Visible = false;
                TotalLbl.Visible = false;
                JumpLB.Visible = false;
                TextBox1.Visible = false;
            }
            else
            {
                FirstLB.Visible = true;
                
                PreviousLB.Visible = true;
                NextLB.Visible = true;
                EndLB.Visible = true;
                TotalLbl.Visible = true;
                JumpLB.Visible = true;
                TextBox1.Visible = true;
            }*/
            DataList1.RepeatColumns = 4;
            DataList1.RepeatDirection = RepeatDirection.Horizontal;
            DataList1.DataBind();
            this.PreviousLB.Enabled = true;
            this.NextLB.Enabled = true;
            this.enable();
        }

        public void enable()
        {
            int CurrIndex = (int)ViewState["CurrPageIndex"];
            int PageCount = (int)ViewState["PageCount"];
            if (CurrIndex == (PageCount - 1))
            {
                this.NextLB.Enabled = false;//当为最后一页时，下一页链接按钮不可用
            }
            if (CurrIndex == 0)
            {
                this.PreviousLB.Enabled = false;//当为第一页时，上一页按钮不可用
            }
            this.CurrentLbl.Text = (CurrIndex + 1).ToString();//当前页数
            this.TotalLbl.Text = PageCount.ToString();
        }

        //protected void AddCartButton_Click(object sender, EventArgs e)
        //{

        //}
        public void LinkButton_Click(Object sender, CommandEventArgs e)//自己编写的按钮点击事件
        {
            CurrentPageIndex = (int)ViewState["CurrPageIndex"];     //获得当前页索引
            string cmd = e.CommandName;         //判断cmd，以判定翻页方向
            switch (cmd)
            {
                case "prev"://上一页
                    if (CurrentPageIndex > 0)
                    {
                        CurrentPageIndex--;
                    }
                    break;
                case "next":
                    if (CurrentPageIndex < (pds.PageCount - 1))
                    {
                        CurrentPageIndex++;            //下一页
                    }
                    break;
                case "first":                          //第一页
                    CurrentPageIndex = 0;
                    break;
                case "end":                            //最后一页
                    CurrentPageIndex = pds.PageCount - 1;
                    break;
                case "jump":                          //跳转到第几页
                    if (this.TextBox1.Text.Trim() == "" || Int32.Parse(this.TextBox1.Text.Trim()) > pds.PageCount)//如果输入数字为空或超出范围则返回
                    {
                        return;
                    }
                    else
                    {
                        CurrentPageIndex = Int32.Parse(this.TextBox1.Text.ToString()) - 1;
                    }
                    break;
            }
            ViewState["CurrPageIndex"] = CurrentPageIndex;      //获得当前页的索引
            this.DataListBind();  //重新将DataList绑定数据   刷新显示

        }

        protected void addInCart(object source, DataListCommandEventArgs e)
        {


        }

        protected void addInCartEvent(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "addoneitem")
            {
                if (Session["User"] == null)    //是否登录
                {

                    Response.Write("<script>top.location=\"Port.aspx?mod=Login\";</script>");
                }
                else
                {
                    User user = (User)Session["User"];
                    int userid = user.UserID;
                    //获取到一个item中的控件
                    Label Lbl_GoodsName = e.Item.FindControl("Label_GoodsName") as Label;
                    String goodname = Lbl_GoodsName.Text;
                    SqlIt sql = new SqlIt();
                    //这里居然是使用商品名获取ID的，服了
                    String goodid = sql.SingleSpecialItem("GoodsInfo", "GoodsName='" + goodname + "'", "ID").ToString();
                    //先要根据商品名获取

                    DataSet a1 = new DataSet();
                    a1 = sql.SpecialItem("GoodsInfo", "ID='" + goodid + "'", "*");
                    if (a1.Tables[0].Rows.Count != 0)
                    {
                        Dictionary<string, string> myDic = new Dictionary<string, string>();

                        myDic["UserID"] = Convert.ToString(userid);
                        myDic["GoodsID"] = goodid;

                        int saleMethod = Convert.ToInt32(a1.Tables[0].Rows[0]["SaleMethod"]);
                        if (saleMethod == 0 || saleMethod == 1)
                        {
                            myDic["Amount"] = "1";
                        }
                        else
                        {
                            myDic["Weight"] = "1";
                        }
                        sql.AddMess("CartInfo", myDic);
                        Response.Write("<script type='text/javascript'>alert('成功！');</script>");
                        goodsinfo = JsonConvert.GetGoodsInfoJson(((User)Session["User"]).UserID);
                    }
                }
            }
        }
    }
}